//
//  LKMapViewController.m
//  LKIntelligentVideoProject
//
//  Created by she1323 on 2018/9/19.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKMapViewController.h"
#import "LKMapSearchViewController.h"
#import "LKMapBottomListCell.h"
#import "LKCustomAnnotationView.h"
#import "BMKClusterManager.h"
#import "LKCluster.h"
#import "LKClusterAnnotation.h"
#import "LKClusterAnnotationView.h"
#import "LKMonitorVideoPlayerViewController.h"
#import "JZLocationConverter.h"
#import "LKSelectVideoAnnotationViewController.h"
#import <MJRefresh.h>
#define BMKAppkey @"Xs8oK7p5KvjwoCLmU8d1GfwErmCiZ5Ru"
static NSString * const cellID = @"cellID";
static NSString * const cell2ID = @"cell2ID";

@interface LKMapViewController ()<BMKMapViewDelegate,BMKRouteSearchDelegate,UITableViewDelegate,UITableViewDataSource,BMKPoiSearchDelegate,BMKLocationManagerDelegate,BMKLocationAuthDelegate,BMKGeoCodeSearchDelegate,LKClusterAnnotationViewDelegate,UITabBarDelegate>{
    BMKClusterManager *_clusterManager;//点聚合管理类
    
    NSInteger _clusterZoom;//聚合级别
    
    CGFloat _clusterFloatZoom;//百度地图聚合的浮点数级别
    
    NSMutableArray *_clusterCaches;//点聚合缓存标注
    
    NSInteger _previousZoom;
    // 记录前一次的缩放等级
    
}

@property(nonatomic,weak) BMKMapView *mapView;//地图

@property(nonatomic,strong) BMKLocationManager *locationManager;//定位

@property(nonatomic,weak) UITableView *tableView;

@property(nonatomic,strong) BMKGeoCodeSearch *searcher;//编码

@property(nonatomic,strong) NSMutableArray<LKMapPointModel *> *dataList;//信息

@property (nonatomic, assign) NSIndexPath *selectIndex;//单选，当前选中的行

@property(nonatomic,strong)BMKUserLocation *userLocation;

@property(nonatomic,strong)BMKPoiSearch *poiSearch;

@property(nonatomic,strong)NSMutableArray<LKCustomAnnotationView *> *annationsArray;

@property(nonatomic,strong)UISegmentedControl *segmentControl;

@property(nonatomic,assign)NSInteger selectedSeg;//选中的segmentcontrol

@property(nonatomic,assign)BOOL isFirstLoad;

@property(nonatomic,assign)NSInteger PageIndex;

@end

@implementation LKMapViewController{
    UIView *_topbgView;
    NSString *_cityName;
    BOOL _isAutoMove;
}

#pragma mark - 监听方法

- (void)clickSearch{
    
    LKMapSearchViewController *mapSearchVC = [[LKMapSearchViewController alloc]init];
    mapSearchVC.cityName = _cityName;
    [self.navigationController pushViewController:mapSearchVC animated:NO];
    WS(weakSelf)
    mapSearchVC.chooseAddress = ^(CLLocationCoordinate2D pt) {
        self->_pt = pt;
        BMKReverseGeoCodeSearchOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeSearchOption alloc]init];
        //地理逆向编码
        BMKCoordinateSpan span = BMKCoordinateSpanMake(pt.latitude, pt.longitude);
        BMKCoordinateRegion regions = BMKCoordinateRegionMake(pt, span);
        reverseGeoCodeSearchOption.location = regions.center;
        BOOL flag = [weakSelf.searcher reverseGeoCode:reverseGeoCodeSearchOption];
        if(flag){
            NSLog(@"反geo检索发送成功");
        }else{
            NSLog(@"反geo检索发送失败");
        }
    };
}



/**
 地图定位的BMKLocationManager代理方法的实现

 */
-(void)BMKLocationManager:(BMKLocationManager *)manager didUpdateLocation:(BMKLocation *)location orError:(NSError *)error{
    if (error) {
        NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
    }
    if (!location) {
        return;
    }
    if (!self.userLocation) {
        self.userLocation = [[BMKUserLocation alloc] init];
        self.userLocation.location = location.location;
    }
    [self.mapView updateLocationData:self.userLocation];
    [self getMapDeviceListDataWithType:self.selectedSeg];
    if (_pt.latitude == 0) {
            [self.mapView setCenterCoordinate:self.userLocation.location.coordinate animated:YES];
    }else{
        [self.mapView setCenterCoordinate:self.pt animated:YES];
    }

     [self.locationManager stopUpdatingLocation];
    
}



#pragma mark - BMKGeoCodeSearchDelegate
//接收反向地理编码BMKGeoCodeSearch结果
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        
        _cityName = result.addressDetail.city;
        
        return;
        
    }
    else {
        NSLog(@"抱歉，未找到结果");
    }
}
//地图大头针的设置
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation{
    NSString *AnnotationViewID = @"ClusterMark";
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        LKClusterAnnotation *cluster = (LKClusterAnnotation*)annotation;
        LKCustomAnnotationView *annotationView = [[LKCustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        annotationView.canShowCallout = YES;
        annotationView.annotation = cluster;
        cluster.size = 1;
        if ([cluster.title isEqual:@"井盖"]) {
          annotationView.image = [UIImage imageNamed:@"jinggai"];
        }else if ([cluster.title isEqual:@"门禁"]){
           annotationView.image = [UIImage imageNamed:@"menjin"];
        }else if([cluster.title isEqual:@"监控"]){
           annotationView.image = [UIImage imageNamed:@"shexiangtou"];
        }else if([cluster.title isEqual:@"机房"]){
            if ([[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] != nil) {
                BOOL showHouse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] boolValue];
                if (showHouse) {
                    annotationView.image = [UIImage imageNamed:@"WechatIMG4"];
                }else{
                    annotationView.image = [UIImage imageNamed:@""];
                }
            }else{
                annotationView.image = [UIImage imageNamed:@"WechatIMG4"];
            }
            
        }else{
            
        }
        if (1 == 1) {
            CGRect textrect = [cluster.mappointModel.unitAddr boundingRectWithSize:CGSizeMake( WIDTH / 2 + WIDTH / 4,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
            UIView *paopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 2 + WIDTH / 4, textrect.size.height + 100)];
            paopView.backgroundColor = [UIColor whiteColor];
            BMKActionPaopaoView *pp = [[BMKActionPaopaoView alloc] initWithCustomView:paopView];
            annotationView.paopaoView = pp;
            UILabel *titleLabel = [[UILabel alloc] init];
            titleLabel.numberOfLines = 0;
            titleLabel.font = [UIFont systemFontOfSize:15];
            titleLabel.text = [NSString stringWithFormat:@"地址:%@",cluster.mappointModel.unitAddr];
            [paopView addSubview:titleLabel];
            [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(paopView.mas_top).offset(10);
                make.left.equalTo(paopView.mas_left).offset(5);
                make.width.mas_equalTo(paopView).multipliedBy(0.7);
            }];
            UILabel *statuLabel = [[UILabel alloc] init];
            if ([cluster.mappointModel.alarmStatus isEqual:@"0"]) {
                statuLabel.textColor = [UIColor redColor];
            }else{
                statuLabel.textColor = [UIColor blueColor];
            }
            
            statuLabel.font = [UIFont systemFontOfSize:15];
            
//            NSString * statuStr = [NSString stringWithFormat:@"处理状态:%@",[cluster.mappointModel.alarmStatus isEqual:@"0"] ? @"未处理":@"已处理"];
            NSString * statuStr;
            if ([cluster.mappointModel.alarmStatus isEqual:@"0"]) {
                statuStr = @"处理状态:未处理";
            }else if ([cluster.mappointModel.alarmStatus isEqual:@"1"]){
                statuStr = @"处理状态:处理中";
            }else{
                statuStr = @"处理状态:正常使用";
            }
            NSMutableAttributedString *statuattrStr = [[NSMutableAttributedString alloc] initWithString:statuStr];
            [statuattrStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 5)];
            statuLabel.attributedText = statuattrStr;
            [paopView addSubview:statuLabel];
            [statuLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(titleLabel.mas_left);
                make.top.equalTo(titleLabel.mas_bottom).offset(10);
                make.width.mas_equalTo(paopView).multipliedBy(0.5);
            }];
            UILabel *gradeLabel = [[UILabel alloc] init];
            if ([cluster.mappointModel.alarmStatus isEqual:@"0"]) {
                
                gradeLabel.textColor = [UIColor redColor];
            }else if([cluster.mappointModel.alarmStatus isEqual:@"1"]){
                gradeLabel.textColor = [UIColor redColor];
            }else{
                gradeLabel.textColor = [UIColor blueColor];
            }
            if (cluster.mappointModel.doorStatus) {
                gradeLabel.textColor = [UIColor lightGrayColor];
            }
            gradeLabel.font = [UIFont systemFontOfSize:15];
            NSString *gradeStr = [NSString stringWithFormat:@"处理等级:%@",cluster.mappointModel.alarmGradeString];
            NSMutableAttributedString *gradeAttribuStr = [[NSMutableAttributedString alloc] initWithString:gradeStr];
            [gradeAttribuStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 5)];
            gradeLabel.attributedText = gradeAttribuStr;
            if ([cluster.mappointModel.alarmStatus isEqual:@"2"]) {
                gradeLabel.textColor = [UIColor blueColor];
                NSMutableAttributedString *normalAttribuStr = [[NSMutableAttributedString alloc] initWithString:@"处理等级:正常使用"];
                [normalAttribuStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 5)];
                gradeLabel.attributedText = normalAttribuStr;
            }
            [paopView addSubview:gradeLabel];
            [gradeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(titleLabel.mas_left);
                make.top.equalTo(statuLabel.mas_bottom).offset(5);
                make.width.mas_equalTo(paopView).multipliedBy(0.5);
            }];
            UIImageView *imageV = [[UIImageView alloc] init];
            imageV.image = annotationView.image;
            imageV.userInteractionEnabled = YES;
            [paopView addSubview:imageV];
            [imageV mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(paopView.mas_right).offset(-10);
//                make.top.equalTo(statuLabel.mas_top);
                make.centerY.equalTo(paopView);
            }];
            WS(weakSelf)
            if ([cluster.title isEqual:@"井盖"]) {
                if ([cluster.mappointModel.alarmStatus isEqual:@"2"]) {
                    
                    annotationView.image = [UIImage imageNamed:@"WechatIMG1"];
                    imageV.image = [UIImage imageNamed:@"WechatIMG1"];
                    [imageV mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.right.equalTo(paopView.mas_right).offset(-10);
//                        make.bottom.equalTo(paopView.mas_bottom).offset(-10);
                        make.centerY.equalTo(paopView);
                    }];
                }else{
                    
                }
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
<<<<<<< HEAD
                    
                    SS(strongSelf)
                    NSDictionary *param = @{@"code":@"cover",@"roleId":[LKUserInforTool account].roleId};
                    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
                        
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                        if ([responseObject[@"code"] isEqual:@"0000"]) {
//                            [SVProgressHUD showWithStatus:@"井盖处理中"];
                            NSString *alertStr;
                            if ([cluster.mappointModel.alarmStatus isEqual:@"0"]) {
                                alertStr = @"是否标记为处理中";
                            }else if ([cluster.mappointModel.alarmStatus isEqual:@"1"]){
                                alertStr = @"是否标记为已处理";
                            }else{
                                return ;
                            }
                            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:alertStr preferredStyle:UIAlertControllerStyleAlert];
                            [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                                
                            }]];
                            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                NSDictionary *param;
                                if ([cluster.mappointModel.alarmStatus isEqual:@"0"]) {
                                    param = [NSDictionary dictionaryWithObjectsAndKeys:cluster.mappointModel.Id,@"id",@"1",@"alarmStatus", nil];
                                }else if ([cluster.mappointModel.alarmStatus isEqual:@"1"]){
                                    param = [NSDictionary dictionaryWithObjectsAndKeys:cluster.mappointModel.Id,@"id",@"2",@"alarmStatus", nil];
                                }else{
                                    return ;
                                }
                                [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/coverAlarm/server/app/dealAlarmStatus" parameters:param progress:^(NSProgress * _Nullable progress) {

                                } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                                    if ([responseObject[@"code"] isEqual:@"0000"]) {
                                        [SVProgressHUD showInfoWithStatus:@"处理成功"];
                                        if ([cluster.mappointModel.alarmStatus isEqual:@"0"]) {
                                            cluster.mappointModel.alarmStatus = @"1";
                                        }else{
                                            cluster.mappointModel.alarmStatus = @"2";
                                        }
                                        //                                    cluster.mappointModel.alarmStatus = @"1";
                                        NSString *gradeStr = [NSString stringWithFormat:@"处理等级:%@",cluster.mappointModel.alarmGradeString];
                                        NSMutableAttributedString *gradeAttribuStr = [[NSMutableAttributedString alloc] initWithString:gradeStr];
                                        [gradeAttribuStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 5)];
                                        gradeLabel.attributedText = gradeAttribuStr;
                                        if ([cluster.mappointModel.alarmStatus isEqual:@"1"]) {
                                            gradeLabel.textColor = [UIColor redColor];
                                            statuLabel.textColor = [UIColor redColor];
                                            NSString * statuStr = [NSString stringWithFormat:@"处理状态:%@",[cluster.mappointModel.alarmStatus isEqual:@"1"] ? @"处理中":@"正常使用"];
                                            NSMutableAttributedString *statuattrStr = [[NSMutableAttributedString alloc] initWithString:statuStr];
                                            [statuattrStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 5)];
                                            statuLabel.attributedText = statuattrStr;
                                            annotationView.image = [UIImage imageNamed:@"WechatIMG1"];
                                            [strongSelf getMapDeviceListDataWithType:self.selectedSeg];
                                        }else{
                                            gradeLabel.textColor = [UIColor blueColor];
                                            NSMutableAttributedString *normalAttribuStr = [[NSMutableAttributedString alloc] initWithString:@"处理等级:正常使用"];
                                            [normalAttribuStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 5)];
                                            gradeLabel.attributedText = normalAttribuStr;
                                            statuLabel.textColor = [UIColor blueColor];
                                            NSString * statuStr = [NSString stringWithFormat:@"处理状态:%@",[cluster.mappointModel.alarmStatus isEqual:@"1"] ? @"处理中":@"正常使用"];
                                            NSMutableAttributedString *statuattrStr = [[NSMutableAttributedString alloc] initWithString:statuStr];
                                            [statuattrStr addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(0, 5)];
                                            statuLabel.attributedText = statuattrStr;
                                            annotationView.image = [UIImage imageNamed:@"WechatIMG1"];
                                            [strongSelf getMapDeviceListDataWithType:self.selectedSeg];
                                        }
                                    }else{
                                        [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                                    }
                                } failure:^(NSString * _Nullable errorMessage) {

                                }];
                            }]];
                            [self presentViewController:alert animated:YES completion:nil];

                            NSLog(@"点击了井盖的");
                        }else{
                            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                        }
                    } failure:^(NSString * _Nullable errorMessage) {
                        
                    }];

=======
                    SS(strongSelf)
                    NSLog(@"点击了井盖的");
>>>>>>> parent of 2e14138... 提交
                }];
                [imageV addGestureRecognizer:tap];
            }else if ([cluster.title isEqual:@"门禁"]){
                statuLabel.textColor = [UIColor lightGrayColor];
                statuLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"门禁名称:%@",cluster.mappointModel.doorName]];
                gradeLabel.textColor = [UIColor lightGrayColor];
                gradeLabel.attributedText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"门禁状态:%@",cluster.mappointModel.doorStatuString]];
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                    SS(strongSelf)
                    NSLog(@"点击了门禁的");
                    NSDictionary *param = @{@"code":@"guard",@"roleId":[LKUserInforTool account].roleId};
                    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
                        
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
<<<<<<< HEAD
                        if ([responseObject[@"code"] isEqual:@"0000"]) {
                            [SVProgressHUD showWithStatus:@"门禁处理中"];
                            NSString *commandStr = [cluster.mappointModel.doorStatus isEqual:@"1"] ? @"2":@"1";
                            LKUserInfor *userInfor = [LKUserInforTool account];
                            NSDictionary *param = @{@"command":commandStr,@"userUuid":userInfor.userUuid,@"doorUuid":cluster.mappointModel.doorUuid};
                            [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/unitInfo/server/app/synControl" parameters:param progress:^(NSProgress * _Nullable progress) {
                                
                            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                                
                                if ([responseObject[@"code"] isEqual:@"0000"]) {
                                    [SVProgressHUD showInfoWithStatus:@"处理成功"];
                                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                        [strongSelf getMapDeviceListDataWithType:strongSelf.selectedSeg];
                                    });
                                    
                                }else{
                                    [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                                    
                                }
                                
                            } failure:^(NSString * _Nullable errorMessage) {
                                
                            }];
                        }else{
                            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                        }
=======
                        [SVProgressHUD showInfoWithStatus:@"处理成功"];
                        [strongSelf getMapDeviceListData];
                        
>>>>>>> parent of 2e14138... 提交
                    } failure:^(NSString * _Nullable errorMessage) {
                        
                    }];


                }];
                if ([cluster.mappointModel.doorStatus isEqual:@"2"]) {
                    imageV.image = [UIImage imageNamed:@"tapOpenDoor"];
                }else{
                    imageV.image = [UIImage imageNamed:@"tapCloseDoor"];
                }
                [imageV addGestureRecognizer:tap];
            }else if ([cluster.title isEqual:@"监控"]){
                [statuLabel removeFromSuperview];
                [gradeLabel removeFromSuperview];
                [titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(paopView.mas_top).offset(10);
                    make.left.equalTo(paopView.mas_left).offset(5);
                    make.right.equalTo(paopView.mas_right).offset(-5);
                }];
                [imageV mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(titleLabel.mas_bottom).offset(5);
                    make.centerX.equalTo(paopView.mas_centerX);
                }];
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
                    SS(strongSelf)
<<<<<<< HEAD
                    NSDictionary *param = @{@"code":@"video",@"roleId":[LKUserInforTool account].roleId};
                    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
                        
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                        if ([responseObject[@"code"] isEqual:@"0000"]) {
                            LKSelectVideoAnnotationViewController *vc = [[LKSelectVideoAnnotationViewController alloc] init];
                            vc.playAddr = cluster.mappointModel.playAddr;
                            [strongSelf.navigationController pushViewController:vc animated:YES];
                        }else{
                            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                        }
                    } failure:^(NSString * _Nullable errorMessage) {
                        
                    }];
=======
                    LKSelectVideoAnnotationViewController *vc = [[LKSelectVideoAnnotationViewController alloc] init];
                    [strongSelf.navigationController pushViewController:vc animated:YES];
>>>>>>> parent of 2e14138... 提交
                    NSLog(@"点击了监控的");
                }];
                [imageV addGestureRecognizer:tap];
            }else if([cluster.title isEqual:@"监控"]){
                NSLog(@"你点击了机房");
            }else{
                
            }
        }else {

        }
        return annotationView;
    }

    return nil;
}




/**
 百度地图自定义聚合点大头针的点击代理方法

 @param cluster 聚合点
 @param clusterAnnotationView 聚合点大头针
 */
-(void)didAddreesWithClusterAnnotationView:(LKCluster *)cluster clusterAnnotationView:(LKClusterAnnotationView *)clusterAnnotationView{
    NSLog(@"点击的%@",clusterAnnotationView.title);
}
/**
*地图初始化完毕时会调用此接口
 *@param mapView 地图View
*/
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView {
//    [self updateClusters];
    
}

/**
 *地图渲染每一帧画面过程中，以及每次需要重绘地图时（例如添加覆盖物）都会调用此接口
 *@param mapView 地图View
 *@param status 此时地图的状态
 */
- (void)mapView:(BMKMapView *)mapView onDrawMapFrame:(BMKMapStatus *)status {
    if (_clusterZoom != 0 && _clusterZoom != (NSInteger)mapView.zoomLevel) {
//        [self updateClusters];
    }

}

/**
 *当点击annotation view弹出的泡泡时，调用此接口
 *@param mapView 地图View
 *@param view 泡泡所属的annotation view
 */
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view {
    if ([view isKindOfClass:[LKClusterAnnotationView class]]) {
        LKClusterAnnotation *clusterAnnotation = (LKClusterAnnotation*)view.annotation;
        if (clusterAnnotation.size > 1) {
            [mapView setCenterCoordinate:view.annotation.coordinate];
//            [mapView zoomIn];
        }
    }
}


#pragma mark - BMKMapViewDelegate

- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    BMKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center = centerCoordinate;
    NSLog(@" regionDidChangeAnimated %f,%f",centerCoordinate.latitude, centerCoordinate.longitude);
    
    //发起反向地理编码检索
    BMKReverseGeoCodeSearchOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeSearchOption alloc]init];
    //地理逆向编码
    reverseGeoCodeSearchOption.location = region.center;
    BOOL flag = [self.searcher reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag){
        NSLog(@"反geo检索发送成功");
    }else{
        NSLog(@"反geo检索发送失败");
    }
    
    
    [self updateClusters];
}

//大头针的选中效果
-(void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    WS(weakSelf)
//    LKClusterAnnotationView *anmiationV = (LKClusterAnnotationView *)view;
//    NSLog(@"选中的%@",anmiationV.mappointModel);
}


#pragma mark - UI

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    
    [self.mapView viewWillAppear];
    self.selectIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    self.searcher.delegate = self;
    self.mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    if (_pt.longitude == 0) {
        [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(31.235105, 121.531376) animated:YES];
    }else{
        [self.mapView setCenterCoordinate:_pt animated:YES];
//        [self addSpecailAnnationViewWithModel:self.homeSendModel];
//       [self getMapDeviceListDataWithType:self.selectedSeg];
    }
    
    
    
    
    
    
    NSArray *items;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] != nil) {
        BOOL showHouse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] boolValue];
        if (showHouse) {
            items = @[@"监控",@"门禁",@"井盖",@"机房"];
        }else{
            items = @[@"监控",@"门禁",@"井盖"];
        }
    }else{
        items = @[@"监控",@"门禁",@"井盖",@"机房"];
    }

    _segmentControl = [[UISegmentedControl alloc] initWithItems:items];
    _segmentControl.apportionsSegmentWidthsByContent = YES;
//    _segmentControl.selectedSegmentIndex = self.selectedSeg;
        _segmentControl.selectedSegmentIndex = 0;
    [_segmentControl addTarget:self action:@selector(chooseDiffrentType:) forControlEvents:UIControlEventValueChanged];

}

/**
 接受是否显示机房的通知变化
 */
-(void)showHouseNot{
    NSArray *items;
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] != nil) {
        BOOL showHouse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] boolValue];
        if (showHouse) {
            items = @[@"监控",@"门禁",@"井盖",@"机房"];
        }else{
            items = @[@"监控",@"门禁",@"井盖"];
        }
    }else{
        items = @[@"监控",@"门禁",@"井盖",@"机房"];
    }
    self.selectedSeg = 0;
    _segmentControl = [[UISegmentedControl alloc] initWithItems:items];
    _segmentControl.apportionsSegmentWidthsByContent = YES;
    _segmentControl.selectedSegmentIndex = 0;
    [_segmentControl addTarget:self action:@selector(chooseDiffrentType:) forControlEvents:UIControlEventValueChanged];
    [self getMapDeviceListDataWithType:self.selectedSeg];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    [self.mapView viewWillDisappear];
    self.mapView.delegate = nil; // 不用时，置nil
    self.searcher.delegate = nil;
}

+(void)initialize{
    //个性化地图模板文件路径
    
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"mapStyle" ofType:@"json"];
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"custom_config_0323(黑夜)" ofType:@""];
//    //设置个性化地图样式
//    [BMKMapView customMapStyle:path];

}
- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"地图";
    self.isFirstLoad = YES;
    self.selectedSeg = 0;
    self.PageIndex = 1;
    _clusterZoom = 3;
    
    [self setupMapView];
    [self setupSearchView];
    [self setupTableView];
//    [self setUpClusterManagers];
    //启动LocationService
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:BMKAppkey authDelegate:self];
    [self.locationManager startUpdatingLocation];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showHouseNot) name:@"showHouseActionNotice" object:nil];
    
}

- (void)setupSearchView {
    UIView *topView = [[UIView alloc]init];
    topView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(STATUS_BAR_HEIGHT);
        make.height.offset(40);
    }];
    _topbgView = topView;
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"mapBack"] forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    backBtn.backgroundColor = [UIColor whiteColor];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [backBtn addTarget:self action:@selector(backback:) forControlEvents:UIControlEventTouchUpInside];
    [_topbgView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self->_topbgView.mas_left).offset(10);
        make.centerY.equalTo(self->_topbgView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    UIView *searchView = [[UIView alloc]init];
    searchView.backgroundColor = [UIColor whiteColor];
    [topView addSubview:searchView];
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(topView);
        make.left.equalTo(backBtn.mas_right).offset(10);
        make.right.equalTo(topView).offset(-10);
        make.height.mas_equalTo(@40);
    }];
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickSearch)];
    [gesture setNumberOfTapsRequired:1];
    [searchView addGestureRecognizer:gesture];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"请输入关键字";
    label.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    label.textColor = [UIColor colorWithRed:204/255.0 green:204/255.0 blue:204/255.0 alpha:1/1.0];
    [searchView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(searchView);
    }];
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"withicon2"]];
    [searchView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(searchView);
        make.right.equalTo(label.mas_left).offset(-12);
    }];
}
//设置初始化地图
- (void)setupMapView{
//    BMKWalkCycleRouteGuidanceDelegate
    BMKMapView *mapView = [[BMKMapView alloc]init];
    [self.view addSubview:mapView];
    [mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsZero);
    }];
    BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
    param.isAccuracyCircleShow = NO;
    param.accuracyCircleStrokeColor = [UIColor clearColor];
    param.accuracyCircleFillColor = [UIColor clearColor];
    [mapView updateLocationViewWithParam:param];
    self.mapView = mapView;
    self.mapView.delegate = self;
    [self.mapView setMapType:BMKMapTypeStandard];
    self.mapView.trafficEnabled = NO;
    self.mapView.showMapPoi = YES;
    self.mapView.zoomLevel = 18;
    self.mapView.rotateEnabled = NO;
    self.mapView.scrollEnabled = YES;
    [self.mapView setTrafficEnabled:NO];
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = BMKUserTrackingModeFollow;
    [BMKMapView enableCustomMapStyle:YES];

    
    [self.mapView setTrafficEnabled:NO];
    
    UIButton *button = [[UIButton alloc]init];
    [button setImage:[UIImage imageNamed:@"gpers_icon"] forState:UIControlStateNormal];
    [mapView addSubview:button];
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(mapView);
    }];

}
//设置初始化tableview
- (void)setupTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(10, NAVIGATION_BAR_HEIGHT + HEIGHT / 2, WIDTH - 20, HEIGHT - NAVIGATION_BAR_HEIGHT - HEIGHT / 2) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    
    [tableView registerNib:[UINib nibWithNibName:@"LKMapBottomListCell" bundle:nil] forCellReuseIdentifier:@"LKMapBottomListCell"];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
}
/**
 头部下拉刷新
 */
-(void)headerReloadData{
    self.PageIndex = 1;
    [self getMapDeviceListDataWithType:self.selectedSeg];
}

/**
 尾部上拉加载更多
 */
-(void)footerReloadData{
    self.PageIndex++;
    [self getMapDeviceListDataWithType:self.selectedSeg];
}

#pragma mark - UITableViewDelegate && dataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKMapBottomListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMapBottomListCell"];
    cell.model = self.dataList[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    _isAutoMove = YES;
    WS(weakSelf)
    LKMapPointModel *poiInfor = self.dataList[indexPath.row];
    for (LKCustomAnnotationView *clusItem in self.annationsArray) {
        if (clusItem.coor.latitude == [poiInfor.unitLatitude floatValue] && clusItem.coor.longitude == [poiInfor.unitLongitude floatValue]) {
            BMKPointAnnotation *pointAnnotation = [[BMKPointAnnotation alloc] init];
            pointAnnotation.coordinate = clusItem.coor;
//            LKClusterAnnotation *selectAnnotation = (LKClusterAnnotation *)pointAnnotation;
            [self.mapView selectAnnotation:pointAnnotation animated:YES];

            [self.mapView setCenterCoordinate:pointAnnotation.coordinate];
            self.mapView.zoomLevel = 18;
            [UIView animateWithDuration:1 animations:^{
                [weakSelf.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(TAB_BAR_HEIGHT + 50);
                    make.bottom.equalTo(weakSelf.view.mas_bottom).offset(0);
                    make.left.equalTo(weakSelf.view).offset(10);
                    make.right.equalTo(weakSelf.view).offset(-10);
                }];
                [weakSelf.tableView.superview layoutIfNeeded];
            }];

        }
    }

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return 105;
    return 80;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor lightGrayColor];
    [headerView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerView).offset(10);
        make.centerX.equalTo(headerView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(100, 10));
    }];
    lineView.layer.cornerRadius = 5;
    lineView.layer.masksToBounds = YES;
    UILabel *countLabel = [[UILabel alloc] init];
    countLabel.text = [NSString stringWithFormat:@"%lu个设备",(unsigned long)self.dataList.count];
    countLabel.textColor = lightGrayDefault;
    countLabel.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:countLabel];
    [countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(headerView.mas_bottom).offset(-10);
        make.top.equalTo(lineView.mas_bottom).offset(10);
        make.centerX.equalTo(headerView.mas_centerX);
    }];
    UIView *bottomlineView = [[UIView alloc] initWithFrame:CGRectMake(0, 54, WIDTH, 1)];
    bottomlineView.backgroundColor = [UIColor lightGrayColor];
    [headerView addSubview:bottomlineView];
    UIPanGestureRecognizer *panges = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pangesAction:)];
    [headerView addGestureRecognizer:panges];
    [headerView addSubview:self.segmentControl];
//    self.segmentControl.selectedSegmentIndex = self.selectedSeg;
    if (self.isFirstLoad) {
        self.segmentControl.selectedSegmentIndex = 0;
//        self.isFirstLoad = NO;
    }else{
       self.segmentControl.selectedSegmentIndex = self.selectedSeg;
    }
//        self.segmentControl.selectedSegmentIndex = self.selectedSeg;
    self.segmentControl.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.segmentControl.layer.borderWidth = 0.0000f;
    [self.segmentControl setTintColor:[UIColor lightGrayColor]];
    [self.segmentControl setDividerImage:[UIImage imageNamed:@""] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.segmentControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomlineView.mas_bottom).offset(3);
        make.left.equalTo(headerView.mas_left).offset(5);
        make.right.equalTo(headerView.mas_right).offset(-5);
        make.height.mas_equalTo(50);
    }];
    return headerView;
    
}

/**
 tableview的拖动展示的action

 @param pan 拖动手势
 */
-(void)pangesAction:(UIPanGestureRecognizer *)pan{
    WS(weakSelf)
    UIView *view = pan.view;
    CGPoint currentPoint = [pan translationInView:view.superview];
    [self.view needsUpdateConstraints];
    if (currentPoint.y < 0) {
        __block CGFloat bottomDistan = 0;
        NSArray *viewcontrollers=self.navigationController.viewControllers;
        if (viewcontrollers.count>1) {
            if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {
                [UIView animateWithDuration:1 animations:^{
                    [weakSelf.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(weakSelf.view).offset(NAVIGATION_BAR_HEIGHT + 10);
                        make.left.equalTo(weakSelf.view).offset(10);
                        make.right.equalTo(weakSelf.view).offset(-10);
                        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(0);
                    }];
                    [weakSelf.tableView.superview layoutIfNeeded];
                }];
            }
        }
        else{
            [UIView animateWithDuration:1 animations:^{
                [weakSelf.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(weakSelf.view).offset(NAVIGATION_BAR_HEIGHT + 10);
                    make.left.equalTo(weakSelf.view).offset(10);
                    make.right.equalTo(weakSelf.view).offset(-10);
                    make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-TAB_BAR_HEIGHT);
                }];
                [weakSelf.tableView.superview layoutIfNeeded];
            }];
            //present方式
        }
    }else{
        NSArray *viewcontrollers=self.navigationController.viewControllers;
        if (viewcontrollers.count>1) {
            if ([viewcontrollers objectAtIndex:viewcontrollers.count-1]==self) {
                [UIView animateWithDuration:1 animations:^{
                    [weakSelf.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.height.mas_equalTo(TAB_BAR_HEIGHT + 50);
                        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(0);
                        make.left.equalTo(weakSelf.view).offset(10);
                        make.right.equalTo(weakSelf.view).offset(-10);
                    }];
                    [weakSelf.tableView.superview layoutIfNeeded];
                }];

            }
        }
        else{
            [UIView animateWithDuration:1 animations:^{
                [weakSelf.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo(TAB_BAR_HEIGHT + 50);
                    make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-TAB_BAR_HEIGHT);
                    make.left.equalTo(weakSelf.view).offset(10);
                    make.right.equalTo(weakSelf.view).offset(-10);
                }];
                [weakSelf.tableView.superview layoutIfNeeded];
            }];

            //present方式
        }


    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 55;
    return 110;
}
#pragma mark - lazyLoad

-(BMKLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[BMKLocationManager alloc] init];
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        _locationManager.desiredAccuracy =  kCLLocationAccuracyNearestTenMeters;
        _locationManager.delegate = self;
    }
    return _locationManager;
}


- (BMKGeoCodeSearch *)searcher{
    if (!_searcher) {
        _searcher =[[BMKGeoCodeSearch alloc]init];
    }
    return _searcher;
}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [[NSMutableArray alloc] init];
    }
    return _dataList;
}

-(NSMutableArray<LKCustomAnnotationView *> *)annationsArray{
    if (!_annationsArray) {
        _annationsArray = [[NSMutableArray alloc] init];
    }
    return _annationsArray;
}


-(void)backback:(UIButton *)btn{
    NSArray *viewcontrollers=self.navigationController.viewControllers;
    
    
    if (viewcontrollers.count > 1)
    {
        if ([viewcontrollers objectAtIndex:viewcontrollers.count - 1] == self)
        {
            //push方式
          [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        [self.tabBarController setSelectedIndex:0];
    }
//    [self.navigationController popViewControllerAnimated:YES];
}

/**
 初始化点聚合管理类
 */
-(void)setUpClusterManagers{
    _clusterCaches = [[NSMutableArray alloc] init];
    for (NSInteger i = 3; i < 22; i++) {
        [_clusterCaches addObject:[NSMutableArray array]];
    }
    
//    点聚合管理类
    _clusterManager = [[BMKClusterManager alloc] init];
}
//更新聚合状态
- (void)updateClusters {
    
//    @synchronized(_clusterCaches) {
//        __block NSMutableArray *clusters = [_clusterCaches objectAtIndex:(_clusterZoom - 3)];
//        if (clusters.count > 0) {
//            [_mapView removeAnnotations:_mapView.annotations];
//            [_mapView addAnnotations:clusters];
//            return;
//        }
//        dispatch_async(dispatch_get_global_queue(0, 0), ^{
//            ///获取聚合后的标注
//            __block NSArray *array = [self->_clusterManager getClusters:self->_clusterZoom];
//            WS(weakSelf)
//            dispatch_async(dispatch_get_main_queue(), ^{
//                for (BMKCluster *item in array) {
//                    LKClusterAnnotation *annotation = [[LKClusterAnnotation alloc] init];
//                    annotation.size = item.size;
//                    if (item.size == 1) {
//                        BMKClusterItem *detailItem = item.clusterItems[0];
//                        annotation.title = detailItem.deviceType;
//                        annotation.mappointModel = detailItem.mapPointModel;
//                    }else{
//
//                    }
//                    annotation.coordinate = item.coordinate;
//                    [clusters addObject:annotation];
//                }
//                [weakSelf.mapView removeAnnotations:weakSelf.mapView.annotations];
//                [weakSelf.mapView addAnnotations:clusters];
//            });
//        });
//    }

}




- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 40.0f, 40.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

/**
 获取地图设备的数据列表
 */
-(void)getMapDeviceListDataWithType:(NSInteger) type{
    LKUserInfor *user = [LKUserInforTool account];
<<<<<<< HEAD
    /**
     设备类型
     1.井盖
     2.门禁
     3.监控
     4.机房
     */
    NSString *unitType;
    NSString *currentPage = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *limit = [NSString stringWithFormat:@"%d",10];
    if (type == 0) {
        unitType = @"3";
    }else if (type == 1){
        unitType = @"2";
    }else if (type == 2){
        unitType = @"1";
    }else{
        unitType = @"4";
    }
//    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:user.loginAccount,@"loginAccount",user.userUuid,@"userUuid", nil];
    NSDictionary * param = @{@"roleId":[LKUserInforTool account].roleId,@"userUuid":[LKUserInforTool account].userUuid,@"page":currentPage,@"limit":limit,@"callSource":@"1",@"unitType":unitType,@"showPlace":@"2"};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/unitInfo/server/app/getUnitInfoByRoleId" parameters:param progress:^(NSProgress * _Nullable progress) {
=======
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:user.userName,@"loginAccount",user.userUuid,@"userUuid", nil];
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/WechatVisitors/unitInfo/getDoorByLoginAccount" parameters:param progress:^(NSProgress * _Nullable progress) {
>>>>>>> parent of 2e14138... 提交
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        self.tableView.mj_footer.hidden = NO;
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (self.PageIndex == 1) {
            [self.dataList removeAllObjects];
            [self.annationsArray removeAllObjects];
            [self.mapView removeAnnotations:self.mapView.annotations];
        }
        NSArray *dataArra = responseObject[@"data"];
        
        if (![dataArra isKindOfClass:[NSNull class]]) {
            @autoreleasepool{
                for (NSInteger i = 0; i < dataArra.count; i++) {
                    NSDictionary *dic = dataArra[i];
                    LKMapPointModel *model = [LKMapPointModel modelWithDictionary:dic];
                    LKCustomAnnotationView *clusterItem = [[LKCustomAnnotationView alloc] init];
                    clusterItem.mapPointModel = model;
                    clusterItem.coor = CLLocationCoordinate2DMake([model.unitLatitude floatValue], [model.unitLongitude floatValue]);
                    clusterItem.deviceType = [self accoringTypeBackValue:[model.unitType integerValue]];
                    BMKMapPoint point1 = BMKMapPointForCoordinate(self.userLocation.location.coordinate);
                    BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake([model.unitLatitude floatValue], [model.unitLongitude floatValue]));
                    CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
                    model.distance = [NSString stringWithFormat:@"%.2lf米",distance];
                    model.curentPt = self.userLocation.location.coordinate;
                    clusterItem.title = [self accoringTypeBackValue:[model.unitType integerValue]];
                    [self.annationsArray addObject:clusterItem];
                    LKClusterAnnotation *annotation = [[LKClusterAnnotation alloc] init];
                    annotation.size = 1;
                    annotation.mappointModel = model;
                    annotation.title = clusterItem.title;
                    NSLog(@"大头针的名称%@",annotation.title);
                    CLLocationCoordinate2D coor;
                    coor.latitude = [model.unitLatitude doubleValue];
                    coor.longitude = [model.unitLongitude doubleValue];
                    annotation.coordinate = coor;
                    self.mapView.delegate = self;
                    [self.mapView addAnnotation:annotation];                      [self.dataList addObject:model];
                }
            }
            
            [self.dataList sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                LKMapPointModel *model1 = obj1;
                LKMapPointModel *model2 = obj2;
                if ([model1.unitType isEqual:@"1"] && [model2.unitType isEqual:@"1"]) {
                    if ([model1.alarmStatus integerValue] < [model2.alarmStatus integerValue]) {
                        return NSOrderedAscending;
                    }else if ([model1.alarmStatus integerValue] > [model2.alarmStatus integerValue]){
                        return NSOrderedDescending;
                    }else{
                        return NSOrderedSame;
                    }
                }else{
                    if ([model1.distance integerValue] < [model2.distance integerValue]) {
                        return NSOrderedAscending;
                    }else if ([model1.distance integerValue] > [model2.distance integerValue]){
                        return NSOrderedDescending;
                    }else{
                        return NSOrderedSame;
                    }
                }
                
            }];
            
            
            if (dataArra.count < [limit integerValue]) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
//            if (self.bottomlistArray.count == 0) {
//                self.tableView.mj_footer.hidden = YES;
//            }
            [self.tableView reloadData];
        }else{
            [self.dataList removeAllObjects];
            [self.tableView reloadData];
            self.tableView.mj_footer.hidden = YES;
        }
  
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
}

#pragma mark - 更新聚合状态

-(NSString *)accoringTypeBackValue:(NSInteger)value{
    switch (value) {
        case 1:
        {
            return @"井盖";
        }
            break;
        case 2:
        {
            return @"门禁";
        }
            break;
        case 3:
        {
            return @"监控";
        }
            break;
        case 4:
        {
            return @"机房";
        }
            break;
        default:
            break;
    }
    return nil;
}

/**
 根据选择的不同类型获取不同的数据并刷新展示
 
 @param seg seg
 */
-(void)chooseDiffrentType:(UISegmentedControl *)seg{
    self.selectedSeg =seg.selectedSegmentIndex;
    self.PageIndex = 1;
    self.isFirstLoad = NO;
    [self.annationsArray removeAllObjects];
    [self getMapDeviceListDataWithType:self.selectedSeg];
}

/**
 从首页条转过来的单独显示的大头针

 @param model model
 */
-(void)addSpecailAnnationViewWithModel:(LKMapPointModel *)model{
    LKCustomAnnotationView *clusterItem = [[LKCustomAnnotationView alloc] init];
    clusterItem.mapPointModel = model;
    clusterItem.coor = CLLocationCoordinate2DMake([model.unitLatitude floatValue], [model.unitLongitude floatValue]);
    clusterItem.deviceType = [self accoringTypeBackValue:[model.unitType integerValue]];
    BMKMapPoint point1 = BMKMapPointForCoordinate(self.userLocation.location.coordinate);
    BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake([model.unitLatitude floatValue], [model.unitLongitude floatValue]));
    CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
    model.distance = [NSString stringWithFormat:@"%.2lf米",distance];
    model.curentPt = self.userLocation.location.coordinate;
    clusterItem.title = [self accoringTypeBackValue:[model.unitType integerValue]];
    [self.annationsArray addObject:clusterItem];
    LKClusterAnnotation *annotation = [[LKClusterAnnotation alloc] init];
    annotation.size = 1;
    annotation.mappointModel = model;
    annotation.title = clusterItem.title;
    NSLog(@"大头针的名称%@",annotation.title);
    CLLocationCoordinate2D coor;
    coor.latitude = [model.unitLatitude doubleValue];
    coor.longitude = [model.unitLongitude doubleValue];
    annotation.coordinate = coor;
    self.mapView.delegate = self;
    [self.mapView addAnnotation:annotation];
}
-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"释放了");
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
